using System;

namespace Mbs.Messaging.Imp
{
    [Serializable]
    public class DelegateInvoker : IDelegateInvoker
    {
        private DelegateInvoker() { }

        public static IDelegateInvoker Create()
        {
            return new DelegateInvoker();
        }

        public static IDelegateInvoker CreateFormInvoker()
        {
            return new FormInvoker();
        }

        public static IDelegateInvoker CreatePoolInvoker()
        {
            return new PoolInvoker();
        }

        //public static IDelegateInvoker CreateFullPoolInvoker()
        //{
        //    return new FullPoolInvoker();
        //}

        public void Invoke<TMessage>(PreFilterHandler<TMessage>[] filters, PreFilterEventArgs<TMessage> e)
        {
            if (filters == null || filters.Length < 1)

                return;
            foreach (var handler in filters)
            {
                handler(e.Sender, e);
                if (e.Canceled)
                    return;
            }
        }

        public void Invoke<TMessage>(FilterHandler<TMessage>[] filters, ObserverHandler<TMessage> handler, FilterEventArgs<TMessage> e)
        {
            if (filters != null && filters.Length > 0)
            {
                e.Receiver = handler.Target;
                foreach (var item in filters)
                {
                    item(e.Sender, e);
                    if (e.Ignored)
                        return;
                }
                handler(e.Sender, e.Message);
            }
            else
            {
                handler(e.Sender, e.Message);
            }
        }

    }
}
